import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:rjpb/shared/constants/account_constant.dart';

class StorageUtil {
  static final StorageUtil _instance = StorageUtil._internal();
  factory StorageUtil() => _instance;
  StorageUtil._internal();

  SharedPreferences? spInstance;

  Future<SharedPreferences> initSharedPreferences() async {
    return spInstance ??= await SharedPreferences.getInstance();
  }

  static Future<void> init() async {
    await _instance.initSharedPreferences();
  }

  static Future<bool> setItem(String key, dynamic value) async {
    SharedPreferences spInstance = await _instance.initSharedPreferences();
    if (value is String) {
      return spInstance.setString(key, value);
    } else if (value is int) {
      return spInstance.setInt(key, value);
    } else if (value is double) {
      return spInstance.setDouble(key, value);
    } else if (value is bool) {
      return spInstance.setBool(key, value);
    } else if (value is Map || value is List) {
      return spInstance.setString(key, jsonEncode(value));
    }
    return false;
  }

  static Future<dynamic> getItem(String key) async {
    SharedPreferences spInstance = await _instance.initSharedPreferences();
    return spInstance.get(key);
  }

  static Future<bool> removeItem(String key) async {
    SharedPreferences spInstance = await _instance.initSharedPreferences();
    return spInstance.remove(key);
  }

  static Future<bool> clear() async {
    SharedPreferences spInstance = await _instance.initSharedPreferences();
    return spInstance.clear();
  }

  static Future<String> getToken() async {
    SharedPreferences spInstance = await _instance.initSharedPreferences();
    return spInstance.getString(AccountConstant.accessToken) ?? '';
  }

  static Future<bool> setToken(String value) async {
    return setItem(AccountConstant.accessToken, value);
  }

  static Future<bool> removeToken() async {
    return removeItem(AccountConstant.accessToken);
  }
}
